<template>
  <div class="contarner-page" @click.stop="showLanguageHandel">
    <page-header ref="languageRef"></page-header>
    <main>
      <div class="container">
        <div class="content">
          <input
            type="text"
            class="input f-18"
            v-model="input1"
            @blur="handleBlur"
            placeholder="Paste URL Instagram"
          />
          <div class="flex_between">
            <input type="text" class="input f-18" v-model="input2" disabled />
            <div class="open shou" @click="open">open</div>
          </div>
          <textarea class="textarea f-18" v-model="input3"></textarea>
          <div class="flex_ccenter">
            <div class="sendbtn shou" @click="handleSubmit">download</div>
          </div>
        </div>
        <!-- 解析结果 start -->
        <div class="container" v-if="success">
          <success-content
            @refresh="refresh"
            :list="successList"
          ></success-content>
        </div>
        <!-- 解析结果 end -->
      </div>
    </main>
    <footer>
      <div class="container">
        <div class="footer-content">
          <div class="footer-link">
            <div class="row flex_between">
              <div class="col-12">
                <div class="link-label fw700 c-000 f-21">Tools</div>
                <ul class="list-unstyled c-ccc f-16">
                  <li>
                    <nuxt-link to="/instagram-story-download"
                      >Instagram Story Downloader</nuxt-link
                    >
                  </li>
                  <li>
                    <nuxt-link to="/instagram-reels-video-download"
                      >Instagram Reels Downloader</nuxt-link
                    >
                  </li>
                  <li>
                    <a href="https://savingtik.com/" target="_blank"
                      >Tiktok Downloader</a
                    >
                  </li>
                </ul>
              </div>
              <div class="col-6">
                <div class="link-label fw700 c-000 f-21">Support</div>
                <ul class="list-unstyled c-ccc f-16">
                  <li>
                    <nuxt-link to="/contact"> Contact </nuxt-link>
                  </li>
                  <li>
                    <nuxt-link to="/blog"> Blog </nuxt-link>
                  </li>
                </ul>
              </div>
              <div class="col-6">
                <div class="link-label fw700 c-000 f-21">Legal</div>
                <ul class="list-unstyled c-ccc f-16">
                  <li>
                    <nuxt-link to="/terms-of-service">
                      Terms of Service
                    </nuxt-link>
                  </li>
                  <li>
                    <nuxt-link to="/privacy-policy"> Privacy Policy </nuxt-link>
                  </li>
                </ul>
              </div>
            </div>
          </div>
          <div class="copyright flex_ccenter">
            <b class="fw700 f-21 c-000"
              >We are not affiliated with Instagram or Meta</b
            >
            <div class="c-ccc f-16">
              © {{ new Date().getFullYear() }} Insta Downloader All rights
              reserved.
            </div>
          </div>
        </div>
      </div>
    </footer>
    <div id="loadingIndicator" v-if="loading">
      <div class="loading-wrapper">
        <div class="loading-text">Loading...</div>
      </div>
    </div>
  </div>
</template>
          
          <script>
import { mapState, mapGetters, mapMutations } from "vuex";
import pageHeader from "~/components/page-header.vue";
import SuccessContent from "~/components/success-content.vue";

export default {
  components: { pageHeader, SuccessContent },
  head: {
    meta: [
      {
        name: "robots",
        content: "noindex, nofollow",
      },
    ],
  },
  data() {
    return {
      loading: false,
      input1: "",
      input2: "",
      input3: "",
      successList: [],
      success: false,
    };
  },
  computed: {
    ...mapGetters(["language"]),
    canSubmit() {
      // 如果所有输入框都为空，不允许提交
      return this.input1 || this.input2 || this.input3;
    },
  },
  mounted() {},
  methods: {
    refresh(){},
    open(){
      if(!this.input2) return
      window.open(this.input2, '_blank');
    },
    handleBlur() {
      if (!this.input1) return;
      this.input1 = this.input1.replace(/^.*\s?https:\/\//, "https://");
      const insUrlPattern = new RegExp("^http(s|)://.*instagram.com.*/.*$");
      if (!insUrlPattern.test(this.input1)) {
        // 非ins链接
      } else {
        // 是ins链接
        this.input2 = this.convertInstagramURL(this.input1);
      }
    },
    async handleSubmit() {
      // 如果不允许提交，返回不执行后续操作
      if (!this.canSubmit) {
        return;
      }
      // 如果input1，input2，input3全部有值，只处理input3的内容
      if (this.input2 && this.input3) {
        // 这里写上对input3内容的处理逻辑
        this.loading = true;

        try {
          const result = await this.processData(JSON.parse(this.input3));
          this.successList = result;
          if (this.successList.length) {
            this.success = true;
          }
          this.loading = false;
        } catch {
          this.loading = false;
          this.input3 = "";
          alert("输入有误");
        }
      }
      // 根据实际需求添加其他逻辑
    },

    convertInstagramURL(url) {
      // 用于识别和转换 /p/, /reel/, /tv/ 样式的链接
      const mediaRegex =
        /https:\/\/www\.instagram\.com\/(p|reel|tv)\/([a-zA-Z0-9_-]+)\/?.*/;
      const highlightRegex =
        /https:\/\/www\.instagram\.com\/stories\/highlights\/([0-9]+)\/?/;

      if (mediaRegex.test(url)) {
        // 对于 /p/, /reel/, /tv/ 类型的URL进行替换
        return url.replace(
          mediaRegex,
          "https://www.instagram.com/$1/$2/?__a=1&__d=dis"
        );
      } else if (highlightRegex.test(url)) {
        // 对于 /stories/highlights/ 类型的URL进行转换
        const highlightId = url.match(highlightRegex)[1];
        return `https://www.instagram.com/graphql/query/?query_hash=de8017ee0a7c9c45ec4260733d81ea31&variables=${encodeURIComponent(
          JSON.stringify({
            reel_ids: [],
            tag_names: [],
            location_ids: [],
            highlight_reel_ids: [highlightId],
            precomposed_overlay: false,
            show_story_viewer_list: true,
            story_viewer_fetch_count: 50,
            story_viewer_cursor: "",
          })
        )}`;
      } else {
        // 如果链接不符合已知格式，返回原链接
        return url;
      }
    },
    fetchImageBase64(url) {
      return new Promise((resolve, reject) => {
        this.$axios
          .$get(
            `https://savinginsta.com/webapi/convert-to-base64?url=${encodeURIComponent(
              url
            )}`
          )
          .then((base64) => {
            resolve(base64);
          })
          .catch((error) => {
            console.error("Error converting image to Base64:", error);
            reject(error);
          });
      });
    },
    async processData(data) {
      let list = [];
      if (data.items) {
        for (const item of data.items) {
          const userName = item.user.username; // 提取用户名
          const headUrl = await this.fetchImageBase64(
            item.user.profile_pic_url
          ); // 转换头像为Base64

          if (item.media_type === 8 && item.carousel_media) {
            for (const media of item.carousel_media) {
              const mediaUrl =
                media.media_type == 1
                  ? media.image_versions2.candidates[0].url
                  : media.video_versions[0].url;
              const displayUrlmediaUrl =
                media.image_versions2.candidates[0].url;
              // 转换媒体URL为Base64
              const displayUrlBase64 = await this.fetchImageBase64(
                displayUrlmediaUrl
              );
              list.push({
                displayUrl: displayUrlBase64,
                actUrl: mediaUrl,
                headUrl: headUrl,
                isVideo: media.media_type === 2,
                userName: userName,
              });
            }
          } else if (item.media_type === 2 && item.video_versions) {
            const lastVideo = item.video_versions[0].url;
            const lastImage = item.image_versions2.candidates[0].url;
            // 转换封面为Base64
            const displayUrlBase64 = await this.fetchImageBase64(lastImage);
            list.push({
              displayUrl: displayUrlBase64,
              actUrl: lastVideo,
              headUrl: headUrl,
              isVideo: true,
              userName: userName,
            });
          } else if (item.media_type === 1 && item.image_versions2) {
            const lastImage = item.image_versions2.candidates[0].url;
            // 转换封面为Base64
            const displayUrlBase64 = await this.fetchImageBase64(lastImage);
            list.push({
              displayUrl: displayUrlBase64,
              actUrl: lastImage,
              headUrl: headUrl,
              isVideo: false,
              userName: userName,
            });
          }
        }
      } else if (data.data && data.data.reels_media) {
        const username = data.data.reels_media[0].owner.username; // 提取用户名
        const profile_pic_url_base64 = await this.fetchImageBase64(
          data.data.reels_media[0].owner.profile_pic_url
        ); // 转换头像为Base64
        for (const mediaGroup of data.data.reels_media) {
          for (const item of mediaGroup.items) {
            const resource = item.is_video
              ? item.video_resources
              : item.display_resources;
            const lastResource = resource[0];
            // 转换展示图为Base64
            const displayUrlBase64 = await this.fetchImageBase64(
              item.display_url
            );
            list.push({
              displayUrl: displayUrlBase64,
              actUrl: lastResource.src,
              headUrl: profile_pic_url_base64,
              isVideo: item.is_video,
              userName: username,
            });
          }
        }
      }

      return list;
    },
    showLanguageHandel() {
      this.$refs.languageRef.close();
    },
  },
};
</script>
  <style lang="scss" scoped>
input::-webkit-calendar-picker-indicator {
  display: none !important;
}
main {
  .content {
    padding-top: 30px;
    .input {
      border: 1px solid #4a4a4a;
      padding: 20px;
      border-radius: 10px;
      margin-bottom: 20px;
    }
    .textarea {
      padding: 20px;
      width: 100%;
      min-height: 200px;
      max-height: 200px;
    }
    .open{
      padding: 20px;
      border-radius: 10px;
      background-color: #5c72f9;
      margin-bottom: 20px;
      margin-left: 20px;
      color: #fff;
    }
    .sendbtn {
      background-color: #5c72f9;
      color: #fff;
      border-radius: 10px;
      height: 50px;
      line-height: 50px;
      width: 100%;
      margin-top: 20px;
      text-align: center;
    }
  }
}
footer {
  background-color: #f7f6f9;
  .footer-content {
    padding: 50px 0 30px;
    .row {
      display: flex;
      flex-wrap: wrap;
      align-items: flex-start;

      .col-12 {
        flex: 0 0 auto;
        width: 33.33333333%;
      }
      .col-6 {
        flex: 0 0 auto;
        width: 33.33333333%;
      }
      .list-unstyled {
        margin-top: 20px;
        list-style: none;
        li {
          margin-bottom: 20px;
        }
        li:hover {
          color: #6f69e7;
        }
      }
    }
    .copyright {
      margin-top: 40px;
      div {
        margin-top: 8px;
      }
    }
  }
}
// 宽度小于768
@media (max-width: 768px) {
  footer {
    background-color: #f7f6f9;
    .footer-content {
      padding: 50px 0 30px;
      .row {
        display: flex;
        flex-wrap: wrap;
        .col-12 {
          flex: 0 0 auto;
          width: 100%;
        }
        .col-6 {
          flex: 0 0 auto;
          width: 50%;
        }
        .list-unstyled {
          margin-top: 20px;
          list-style: none;
          li {
            margin-bottom: 20px;
          }
        }
      }
      .copyright {
        margin-top: 40px;
        b {
          font-size: 14px !important;
        }
        div {
          margin-top: 8px;
          font-size: 14px !important;
        }
      }
    }
  }
}
/* Loading Indicator Styles */
#loadingIndicator {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.7); /* 黑色背景，70%透明度 */
  z-index: 9999; /* 确保loading覆盖在其他内容上面 */
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
}

.loading-wrapper {
  text-align: center;
}

.loading-text {
  color: white; /* 白色文本 */
  font-size: 1.5em;
}
</style>
          